from urllib.request import urlopen

from django.conf import settings
import logging
import urllib.parse
import json
from itsdangerous import BadData

from oauth import constants
from oauth.exceptions import OAuthQQAPIError
from itsdangerous import TimedJSONWebSignatureSerializer as TJSSerializer

logger = logging.getLogger("django")

class OAuthQQ(object):

    def __init__(self,client_id=None, client_secret=None,redirect_uri=None,state=None):
        # self.client_id = client_id or settings.QQ_CLIENT_ID
        self.client_id = client_id if client_id else settings.QQ_CLIENT_ID
        self.client_secret = client_secret or settings.QQ_CLIENT_SECRET
        self.redirect_uri = redirect_uri or settings.QQ_REDIRECT_URI
        self.state = state or settings.QQ_STATE  # 用于保存登录成功后的跳转页面路径

    def get_login_url(self):

        url = "https://graph.qq.com/oauth2.0/authorize?"
        print(self.client_id)
        params = {
            'response_type': 'code',
            'client_id': self.client_id,
            'redirect_uri': self.redirect_uri,
            'state': self.state,
            'scope': 'get_user_info',
        }

        url += urllib.parse.urlencode(params)
        return url

    def get_access_token(self,code):

        url = 'https://graph.qq.com/oauth2.0/token?'

        params = {
            'grant_type': 'authorization_code',
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            "code" : code,
            'redirect_uri': self.redirect_uri,

        }

        url += urllib.parse.urlencode(params)


        try:
            #发送请求
            resp = urlopen(url)

            # 读取响应体数据
            resp_data = resp.read()
            resp_data=resp_data.decode()

            # 解析
            resp_dict = urllib.parse.parse_qs(resp_data)
        except Exception as e:
            logging.error(e)
            raise OAuthQQAPIError

        access_token = resp_dict.get("access_token")

        return access_token[0]

    def get_openid(self,access_token):
        url = 'https://graph.qq.com/oauth2.0/me?access_token='+access_token

        try:
            resp = urlopen(url)

            resp_data = resp.read()
            resp_data = resp_data.decode()

            # callback( {"client_id": "YOUR_APPID", "openid": "YOUR_OPENID"} )\n;
            resp_dict = json.loads(resp_data[10:-4])


        except Exception as e:
            logging.error(e)
            raise OAuthQQAPIError
        openid = resp_dict.get("openid")
        print(openid)
        return openid

    def generate_bind_user_access_token(self,openid):

        serializer = TJSSerializer(settings.SECRET_KEY,constants.BIND_USER_ACCESS_TOKEN_EXPIES)
        token = serializer.dumps({"openid":openid})
        return token.decode()

    @staticmethod
    def check_bind_user_access_token(access_token):
        serializer = TJSSerializer(settings.SECRET_KEY,constants.BIND_USER_ACCESS_TOKEN_EXPIES)

        try:
            data = serializer.loads(access_token)

        except BadData:
            return None
        else:
            return data["openid"]
